<template>
    <div class="container">
        <base-tree apiPrefix="/sys/dept" class="tree mr-4" @currentChange="selectDept" title="组织机构"></base-tree>

        <div class="right">
            <entity-manager apiPrefix="/sys/user" :fields="fields" :queryFields="queryFields" ref="entityManagerRef" :params="params" operationsWidth="240px">
                <template #rowButtons="{ row }">
                    <el-link type="danger" v-show="row.status && !row.isSuperAdmin" class="mr-2" @click="updateStatus(row, 0)" v-perm="'update'" icon="Remove">
                        停用
                    </el-link>
                    <el-link type="success" v-show="!row.status" class="mr-2" @click="updateStatus(row, 1)" v-perm="'update'" icon="Check">启用</el-link>
                    <el-link type="primary" v-show="!row.isSuperAdmin" @click="goEdit(row)" class="mr-2" v-perm="'update'" icon="Edit">编辑</el-link>
                    <el-link type="warning" v-show="!row.isSuperAdmin" @click="resetPwd(row)" v-perm="'update'" icon="Lock">重置密码</el-link>
                    <el-link type="danger" v-show="!row.isSuperAdmin" @click="doDelete(row)" class="mr-2" v-perm="'delete'" icon="Delete">删除</el-link>
                </template>

                <template #newRemark>
                    <div class="remark-panel">新增用户默认密码为手机号后6位，手机号为空时，默认为abcd@1234</div>
                    <div class="mt-2 color-primary">{{ msg }}</div>
                </template>
            </entity-manager>
        </div>
    </div>
</template>

<script setup name="sysUser">
import BaseTree from "@/components/base-tree.vue";
import * as sysApis from "@/apis/sys.js";
import { ElMessage } from "element-plus";

const msg = ref("");
const fields = [
    // { label: "工号", prop: "code", width: "120px", required: true, unique: true },
    { label: "昵称", prop: "nickname", required: true, width: "200px" },
    {
        label: "手机号",
        prop: "phone",
        width: "200px",
        validation: {
            validator: (rule, val, callback, form) => {
                if (!val) {
                    return callback();
                }

                if (!app.utils.isPhone(val)) {
                    return callback(new Error("手机号无效"));
                }

                // 检查当前手机号是否在本租户下存在
                app.https.get("/sys/user/check-by-phone", { phone: val }).then((resp) => {
                    if (resp?.user) {
                        if (resp.user.id == form.id) {
                            return callback();
                        }

                        if (resp.inNowTenant) {
                            // 在当前租户下已经存在
                            msg.value = "";
                            return callback(new Error("手机号重复"));
                        } else {
                            // 用户已经存在但在当前租户下不存在
                            form.nickname = resp.user.nickname;
                            msg.value = "用户已存在，此操作会将其添加到当前租户";
                        }
                    } else {
                        msg.value = "";
                    }

                    callback();
                });
            },
        },
        required: true,
    },

    { label: "机构", prop: "deptId", type: "tree-select", options: getDeptTree, converter: (val, row) => row.deptName },
    {
        label: "状态",
        prop: "status",
        width: "80px",
        tagType: (val) => {
            return {
                type: val ? "success" : "warning",
                text: val ? "启用" : "停用",
            };
        },
        needNew: false,
    },
    { label: "角色", prop: "roleIds", type: "select", multiple: true, options: sysApis.getRoles, showInTable: false },
    { label: "创建时间", prop: "createTime", width: "200px", needNew: false },
];
const entityManagerRef = ref();
const params = ref({});
const queryFields = [
    { label: "用户名", prop: "username" },
    { label: "手机号", prop: "phone" },
];

function goEdit(row) {
    entityManagerRef.value.goEdit(row);
}

function doDelete(row) {
    entityManagerRef.value.doDelete(row);
}

function updateStatus(row, status) {
    sysApis.updateUserStatus(row.id, status).then((resp) => {
        ElMessage.success("操作成功");
        row.status = status;
    });
}

function getDeptTree() {
    return sysApis.getDeptTree();
}

function selectDept(dept) {
    params.value.deptId = dept.id;
    entityManagerRef.value.reload();
}

// 密码重置
function resetPwd(row) {
    app.confirm("确定重置当前用户密码？").then(() => {
        app.prompt("请输入新密码", {
            inputValidator: (val) => {
                if (!val) {
                    return "新密码不能为空";
                } else if (val.length < 6) {
                    return "新密码长度不能小于6位";
                }
            },
        }).then(({ action, value }) => {
            if (action != "confirm") {
                return;
            } else if (!value) {
                return;
            }

            app.https.get("/sys/user/reset-pwd", { userId: row.id, password: value }).then(() => {
                app.success("密码重置成功");
            });
        });
    });
}
</script>

<style lang="scss" scoped>
.container {
    display: grid;
    grid-template-columns: 260px 1fr;

    .right {
        overflow-x: auto;
    }
}
</style>
